use std::fmt;

/// 自定义错误类型，包含一个描述错误的字符串
#[derive(Debug)]
pub struct Error {
    message: String,
}

impl Error {
    fn new(msg: &str) -> Self {
        Error {
            message: msg.to_string(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for Error {}
impl serde::ser::Error for Error {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        Error::new(&msg.to_string())
    }
}

impl Into<Error> for String {
    fn into(self) -> Error {
        Error {
            message: self
        }
    }
}

impl Into<Error> for &str {
    fn into(self) -> Error {
        Error::new(self)
    }
}

impl serde::de::Error for Error {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        Error::new(&msg.to_string())
    }
}
